<?php

function get_db_conn() {
  if (!isset ($GLOBALS['db_conn'])){
    $GLOBALS['db_conn'] = mysql_connect($GLOBALS['db_ip'], $GLOBALS['db_user'], $GLOBALS['db_pass']);
    mysql_select_db($GLOBALS['db_name'], $GLOBALS['db_conn']);
  }
  return $GLOBALS['db_conn'];
}

function getUser($facebook_uid) {
  $conn = get_db_conn();
  $res = mysql_query('SELECT * FROM user WHERE `facebook_uid`=' . $facebook_uid, $conn);
  $user = mysql_fetch_object($res);

  return $user;
}

function createOrUpdateUser($facebook_uid,$latitude_uid){
   if (getUser($facebook_uid)){
	updateUser($facebook_uid,$latitude_uid);
   } else {
	createUser($facebook_uid,$latitude_uid);
   }
}

function updateUser($facebook_uid,$latitude_uid){
  $conn = get_db_conn();
  $res = mysql_query('UPDATE user SET `latitude_uid`="'. $latitude_uid .'" WHERE `facebook_uid`="'. $facebook_uid .'"' , $conn);
  return $res;
}

function createUser($facebook_uid,$latitude_uid){
  $conn = get_db_conn();
  $res = mysql_query('INSERT INTO user(`facebook_uid`,`latitude_uid`) VALUES ("'. $facebook_uid .'","'. $latitude_uid .'");' , $conn);
  return $res;
}
